package com.ck.common.service.impl;

import com.ck.common.service.ModuleService;
import com.ck.common.service.OperationLogService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.ModuleConstant;
import com.ck.constant.RequestConstant;
import com.ck.dao.ModuleMapper;
import com.ck.exception.ServiceException;
import com.ck.model.common.Module;
import com.ck.model.common.OperationLog;
import com.ck.model.common.User;
import com.ck.model.common.dto.ButtonModuleDTO;
import com.ck.model.common.dto.MenuModuleDTO;
import com.ck.model.common.dto.ModuleDTO;
import com.ck.model.common.vo.RoleModuleTreeVO;
import com.ck.util.HttpUtils;
import com.ck.util.TreeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 模块Service实现类
 *
 * @author dxy
 * @date 2018/6/22 10:11
 */
@Service(value = "moduleService")
public class ModuleServiceImpl implements ModuleService {
	@Autowired
	private ModuleMapper moduleMapper;
	@Autowired
	private OperationLogService operationLogService;

	/**
	 * 保存模块
	 *
	 * @param module Module
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveModule(Module module, HttpServletRequest request) throws ServiceException {
		if (module == null) {
			throw new ServiceException("输入参数不能为空");
		}
		module.setAddTime(System.currentTimeMillis());
		module.setStatus(BusinessConstant.STATUS_ENABLE);
		moduleMapper.insertModule(module);
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		operationLog.setCopmanyCode(loginUser.getCompanyCode());
		operationLog.setOperationContent("保存模块,模块ID为:" + module.getModuleId());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_MENU);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过ID更新模块
	 *
	 * @param module Module
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateModuleById(Module module, HttpServletRequest request) throws ServiceException {
		if (module == null) {
			throw new ServiceException("输入参数不能为空");
		}
		module.setUpdateTime(System.currentTimeMillis());
		moduleMapper.updateModuleById(module);
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		operationLog.setCopmanyCode(loginUser.getCompanyCode());
		operationLog.setOperationContent("修改模块,模块ID为:" + module.getModuleId());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_MENU);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 角色模块列表
	 *
	 * @return List<RoleModuleTreeVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<RoleModuleTreeVO> listAllRoleModule() {
		return moduleMapper.listAllRoleModule(BusinessConstant.STATUS_ENABLE, BusinessConstant.TYPYE_CP);
	}

	/**
	 * 获取模块树列表
	 *
	 * @return List<ModuleDTO>
	 */
	@Override
	public List<ModuleDTO> getTreeList(Long roleId, Integer moduleType) {
		List<ModuleDTO> moduleList = moduleMapper.listModule(BusinessConstant.STATUS_ENABLE, moduleType);
		if (CollectionUtils.isEmpty(moduleList)) {
			return new ArrayList<>();
		}
		//查找角色相关的权限
		if (roleId != null) {
			List<String> moduleIdList = moduleMapper.listModuleIdsByRoleId(roleId);
			if (CollectionUtils.isNotEmpty(moduleIdList)) {
				for (String strModuleId : moduleIdList) {
					if (StringUtils.isBlank(strModuleId)) {
						continue;
					}
					for (ModuleDTO module : moduleList) {
						Long moduleId = module.getModuleId();
						if (moduleId == null) {
							continue;
						}
						if (strModuleId.equals(String.valueOf(moduleId))) {
							module.setChecked(true);
							break;
						}
					}
				}
			}
		}
		return TreeUtils.getTreeList(moduleList);
	}

	/**
	 * 通过模块名称获取模块
	 *
	 * @param moduleName 模块名称
	 * @param moduleType 模块类型
	 * @return Module
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public Module getModuleByModuleName(String moduleName, Integer moduleType) throws ServiceException {
		if (StringUtils.isBlank(moduleName) || moduleType == null) {
			throw new ServiceException("输入参数不能为空");
		}
		return moduleMapper.getModuleByModuleName(moduleName);
	}

	/**
	 * 获取模块的子模块
	 *
	 * @param moduleId 模块ID
	 * @return List<ModuleDTO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<ModuleDTO> listChildrenModule(Long moduleId) throws ServiceException {
		if (moduleId == null) {
			throw new ServiceException("模块ID不能为空");
		}
		return moduleMapper.listChildrenModule(moduleId);
	}

	/**
	 * 通过模块ID获取角色ID列表
	 *
	 * @param moduleId 模块ID
	 * @return List<Long>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<Long> listRoleIdsFromRoleModuleByModuleId(Long moduleId) throws ServiceException {
		if (moduleId == null) {
			throw new ServiceException("模块ID不能为空");
		}
		return moduleMapper.listRoleIdsFromRoleModuleByModuleId(moduleId);
	}

	/**
	 * 通过模块ID删除模块
	 *
	 * @param moduleId 模块ID
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void deleteModuleById(Long moduleId) throws ServiceException {
		if (moduleId == null) {
			throw new ServiceException("模块ID不能为空");
		}
		//检查模块是否有子模块，如果有，不能删除
		List<ModuleDTO> moduleDTOList = listChildrenModule(moduleId);
		if (CollectionUtils.isNotEmpty(moduleDTOList)) {
			throw new ServiceException("该模块有子模块，请先删除该模块的子模块");
		}
		//检查模块是否与角色关联，如果有，不能删除
		List<Long> roleIdList = listRoleIdsFromRoleModuleByModuleId(moduleId);
		if (CollectionUtils.isNotEmpty(roleIdList)) {
			throw new ServiceException("该模块已关联角色，请先解除与角色的关联");
		}
		//删除模块
		moduleMapper.deleteModuleById(moduleId);
	}

	/**
	 * 获取用户所拥有的菜单模块
	 *
	 * @param userId  用户ID
	 * @return List<MenuModuleDTO>
	 */
	@Override
	public List<MenuModuleDTO> listMenuModuleByUserId(Long userId) throws ServiceException {
		if (userId == null) {
			throw new ServiceException("用户ID不能为空");
		}
		//获取用户菜单列表
		List<MenuModuleDTO> menuModuleList = moduleMapper.listMenuModuleByUserId(userId);
		if (CollectionUtils.isNotEmpty(menuModuleList)) {
			return TreeUtils.getTreeList(menuModuleList);
		}
		return new ArrayList<MenuModuleDTO>();
	}

	/**
	 * 通过模块类型获取所有菜单ID
	 * @param moduleType 模块类型（0：创客，1:公司）
	 * @return
	 */
	@Override
	public List<String> listModuleIdByModuleType(Integer moduleType) {
		return moduleMapper.listModuleIdByModuleType(moduleType);
	}

	@Override
	public List<ButtonModuleDTO> listButtonModuleByUserId(Long userId) throws ServiceException {
		return moduleMapper.listButtonModuleByUserId(userId);
	}
}
